package com.yzg.juc;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author misterWei
 * @create 2020年06月27号:21点36分
 * @mailbox forcontinue@163.com
 */
@Slf4j(topic = "c.CountdownLatch")
public class CountdownLatchTest {
    @SneakyThrows
    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(2);
        ExecutorService service = Executors.newScheduledThreadPool(3);
        service.execute(() -> {
            // - 1 操作
            countDownLatch.countDown();
        });
        service.execute(() -> {
            countDownLatch.countDown();
        });
        countDownLatch.await();
        log.info("线程协作");
    }

    /**
     * 高并发测试
     */
    @Test
    public void request2000(){
        CountDownLatch countDownLatch = new CountDownLatch(2000);
        for (int i = 0; i < 2000; i++) {
            int finalI = i;
            new Thread(()->{
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info(String.valueOf(finalI));
            }).start();
        }

        for (int i = 0; i < 2000; i++) {
            countDownLatch.countDown();
        }
    }
}
